<template>
  <div class="fixed-top">
    <van-sticky>
      <van-nav-bar title="圈子">
      </van-nav-bar>
    </van-sticky>


    <van-tabs v-model:active="activeName" @change="onTabChange">

      <van-tab title="求解答" name="a">

        <div class="scroll-container">
          <van-list v-model:loading="loading" finished-text="没有更多了" @load="onLoad">
            <template #default>
              <div class="card-container">
                <router-link v-for="(item, index) in list2" :key="index" :to="'/helpDetails/' + item.id" tag="div"
                             class="card" @click="setActiveIndex(index)">
                  <div class="card-header">
                <span class="author">
                  <img v-if="item.authorImageUrl" :src="item.authorImageUrl" alt="Author Avatar" class="card__avatar"/>
                  {{ item.authorUsername }} | {{ item.time }}
                </span>


                  </div>
                  <div class="card-content">
                    <img :src="item.image" alt="" class="image"/>
                    <h5>{{ item.title }}</h5>
                    <p v-if="!detailVisible || activeIndex !== index">{{ item.content.slice(0, 20) + '...' }}</p>
                    <p v-if="detailVisible && activeIndex === index">{{ item.content }}</p>
                  </div>
                  <div class="card-footer">
                    <div>
                      <van-icon name="like-o" size="16"/>
                      <span class="post-count">{{ item.follow }}</span>
                    </div>
                    <div @click="handleGoods(item.id)">
                      <van-icon name="comment-circle-o" size="30"/>
                    </div>
                  </div>

                </router-link>
              </div>
            </template>
          </van-list>
        </div>

<!--        //加一个按钮，点击跳转到list.vue-->
        <div class="add-button">
          <van-button type="primary" round size="small" @click="selectL">查看问题解答排行榜</van-button>
        </div>

        <van-floating-bubble v-if="activeName === 'a'" icon="chat" @click="onClickTan"/>

      </van-tab>


      <van-tab title="加油站" name="b">
        <div class="banner">
          <div class="banner-content">
            <h1>21天攒图计划招募令</h1>
            <p>每日一画，不画就出局</p>
            <p>来吧，一起坚持21天，做行动派！</p>
            <van-button type="primary" round size="small" @click="navigateToEvent">了解详情</van-button>
          </div>
        </div>
        <div class="scroll-container">
          <van-list v-model:loading="loading" finished="没有更多了" @load="onLoad" :finished-text="finishedText"
                    :error-text="errorText">
            <div class="item" v-for="(item, index) in list1" :key="index" @click="navigateToArticleDetail(item.id)">
                <div class="item-header">
                  <div class="item-header-left">
                    <van-image :src="item.authorImageUrl" round width="40" height="40"/>
                    <span class="item-header-name">{{ item.authorUsername }}</span>
                    <span class="item-header-time">{{ item.createTime }}</span>
                  </div>
                  <van-tag type="primary" round size="small" v-if="item.hot">hot</van-tag>
                </div>
                <div class="item-content">
                  <p>{{ item.content }}</p>
                  <div class="image-wrapper">
                    <van-image :src="item.contentImg" width="200px" height="100px"/>
                  </div>
                  <div class="item-footer">
                    <van-icon name="like-o" size="16" class="icon"/>
                    <span class="icon-text">{{ item.praises }}</span>
                    <van-icon name="star-o" size="16" class="icon"/>
                    <span class="icon-text">{{ item.review }}</span>
                    <van-icon name="chat-o" size="16" class="icon"/>
                    <span class="icon-text">{{ item.collect }}</span>
                    <van-icon name="share-o" size="16" class="icon"/>
                    <span class="icon-text">{{ item.share }}</span>
                  </div>
              </div>
            </div>
          </van-list>
        </div>


        <van-floating-bubble v-if="activeName === 'b'" icon="guide-o" @click="onClickWen"/>
      </van-tab>


      <van-tab title="关注" name="c">

        <div class="scroll-container">
          <van-list v-model:loading="loading" finished-text="没有更多了" @load="onLoad">
            <template #default>
              <div class="card-container">
                <router-link v-for="(item, index) in list2" :key="index" :to="'/helpDetails/' + item.id" tag="div"
                             class="card" @click="setActiveIndex(index)">
                  <div class="card-header">
                <span class="author">
                  <img v-if="item.authorImageUrl" :src="item.authorImageUrl" alt="Author Avatar" class="card__avatar"/>
                  {{ item.authorUsername }} | {{ item.time }}
                </span>


                  </div>
                  <div class="card-content">
                    <img :src="item.image" alt="" class="image"/>
                    <h5>{{ item.title }}</h5>
                    <p v-if="!detailVisible || activeIndex !== index">{{ item.content.slice(0, 20) + '...' }}</p>
                    <p v-if="detailVisible && activeIndex === index">{{ item.content }}</p>
                  </div>
                  <div class="card-footer">
                    <div>
                      <van-icon name="like-o" size="16"/>
                      <span class="post-count">{{ item.follow }}</span>
                    </div>
                    <div @click="handleGoods(item.id)">
                      <van-icon name="comment-circle-o" size="30"/>
                    </div>
                  </div>

                </router-link>
              </div>
            </template>
          </van-list>
        </div>

      </van-tab>
    </van-tabs>
  </div>


</template>

<script setup>
import {ref, onMounted, onBeforeMount} from 'vue';

import {List, Image, Tag, Icon, Button, NavBar, showToast} from 'vant';
import {useRouter} from "vue-router";
import {get,post} from "../../util/request"; // 确保正确导入 Toast


const activeName = ref('b');
const loading = ref(false);
const finishedText = ref('没有更多了');
const errorText = ref('加载失败，请稍后重试');
const list1 = ref([]);
const list2 = ref([]);
const list3 = ref([]);
const router = useRouter();
const detailVisible = ref(true);
const setActiveIndex = (index) => {
  activeIndex.value = index;
  detailVisible.value = true; // 当点击时，假设你想显示完整内容
};
const activeIndex = ref();
// 添加一个状态来存放从服务器获取的文章详情


const navigateToArticleDetail = (id) => {
  router.push({ name: 'postDetails', params: { id: id } })
}

const selectL = () => {
  router.push({ name: 'list' })
}


const onTabChange = (tab) => {
  // 处理标签页切换逻辑
  if (tab === 'b') {
    fetchData(); // 当切换到"加油站"标签时发起请求
  } else if (tab === 'c') {
    // fatchG();
    // 处理"关注
    chatQ()
    //"标签页的逻辑
  } else if (tab === 'a') {
    chatQ()
    // 处理标签页的逻辑
  }
};

const onLoad = () => {
  // 加载更多数据的逻辑，此处示例中未实现具体加载逻辑
};

// 发起请求获取数据的函数
const fetchData = async () => {
  try {
    loading.value = true;
    const response = await get('circle/selectAll');
    if (response.code === 0) {
      list1.value = response.data; // 假设返回的数据直接赋值给list1

      await fetchUserDataForArticles(list1.value);
    } else {
      console.error('Request failed with status:', response.status);
    }
  } catch (error) {
    console.error('There was an error!', error);
  } finally {
    loading.value = false;
  }
};

const fatchG = async () => {

  try {
    loading.value = true;
    const response = await get('circle/selectNew');
    if (response.status === 200) {
      list3.value = response.data.data; // 假设返回的数据直接赋值给list1

    } else {
      console.error('Request failed with status:', response.status);
    }
  } catch (error) {
    console.error('There was an error!', error);
  }
};


const fetchUserDataForArticles = async (articles) => {
  //发起axios

  for (let i = 0; i < articles.length; i++) {
    try {

      get(`user/user/selectUser/${article.userId}`).then(userDataResponse => {
        if (userDataResponse.code === 0) {
          const userData = userDataResponse.data; // 修改这里
          article.value.authorUsername = userData.data.username; // 修改这里
          article.value.authorImageUrl = userData.data.imageUrl; // 修改这里
        } else {
          console.error(`Failed to fetch user data for userId: ${article.userId}`, userDataResponse.data.message);
        }}).catch(function () {
        showToast("查询全部异常")
      });

      const userDataResponse = await get(`user/user/selectUser/${articles[i].userId}`);
      if (userDataResponse.code === 0) {
        const userData = userDataResponse.data;
        articles[i].authorUsername = userData.username;
        articles[i].authorImageUrl = userData.imageUrl;
      } else {
      }

    } catch (error) {
    }
  }
};

const chatQ = async () => {
  try {
    loading.value = true;
    const response = await get('circle/problem/selectProblemList');
    if (response.code === 0) {
      list2.value = response.data; // 假设返回的数据直接赋值给list1
      console.log(list2.value);
      //查询到数据后调用fetchUserDataForArticles方法，将用户名和头像信息添加到list2中，用articleId作为参数
      await fetchUserDataForArticles(list2.value);

      console.log(list2.value);
    } else {
      console.error('Request failed with status:', response.status);
    }
  } catch (error) {
    console.error('There was an error!', error);
  } finally {
    loading.value = false;
  }
};


// 在组件挂载后立即加载数据（如果需要的话）
onMounted(() => {
  if (activeName.value === 'b') {
    fetchData();
  } else if (activeName.value === 'c') {
    fatchG();
    // 处理"关注"标签页的逻辑
  } else if (activeName.value === 'a') {
    chatQ()
    chatR()
    // 处理标签页的逻辑
  }
});


// 新增方法用于处理跳转
const navigateToEvent = () => {
  router.push({name: 'envent'}); // 假设你已经在Vue Router中定义了一个名为'event'的路由
};

const onClickTan = () => {
  router.push({name: 'addCircleArticle'});
}

const onClickWen = () => {
  router.push({name: 'addProblem'});
}

</script>

<style scoped>

.scroll-container {
  max-height: 600px; /* 设置容器的最大高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}

.scroll-container {
  max-height: 600px; /* 设置容器的最大高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}

.icon {
  margin-right: 10px; /* 可选，为了视觉效果添加的样式 */
}

.fixed-top {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

.banner {
  height: 200px;
  background-color: #f0f0f0;
  margin-bottom: 10px;
  border-radius: 10px;
  overflow: hidden;
}

.banner-content {
  padding: 20px;
  text-align: center;
  color: #333;
}

.banner-content h1 {
  font-size: 18px;
  margin-bottom: 10px;
}

.banner-content p {
  font-size: 14px;
  line-height: 1.5;
}

.item {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
}

.item-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.item-header-left {
  display: flex;
  align-items: center;
}

.item-header-name {
  font-weight: bold;
  margin-left: 10px;
}

.item-header-time {
  margin-left: 10px;
  color: #999;
}

.item-content {
  margin-bottom: 10px;
  display: flex;
  flex-direction: column; /* 让内容按列排列 */
}

.item-content p {
  margin-bottom: 5px;
  color: #333;
  text-align: left; /* 添加这一行来使内容靠左对齐 */
}

.item-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.icon {
  margin-right: 5px;
}

.icon-text {
  color: #999;
}


.image-wrapper {
  margin-bottom: 10px; /* 图片与下方内容的间隔 */
}


.post-count {
  margin-left: 4px;
  color: #666;
}

.card__avatar {
  width: 50px; /* 根据需要设置合适的宽度和高度 */
  height: 50px;
  border-radius: 50%; /* 将边框半径设置为50%，即变为圆形 */
  object-fit: cover; /* 确保图片铺满整个圆形区域 */
}

.card-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  padding: 16px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
}

.card-content {
  padding-top: 16px;
}

.image {
  width: 100%;
  height: auto;
}

.card-footer {
  display: flex;
  justify-content: space-between; /* 分布空间，使项目位于容器的两端 */
  align-items: center; /* 垂直居中对齐 */
  padding: 8px 16px; /* 可选：增加内边距以改善视觉效果 */
}


.add-button {
  /* 可选：为按钮容器添加一些外边距，以与其他元素保持一定的间距 */
  margin: 16px auto;
  text-align: center; /* 使按钮居中显示 */

  /* 如果需要固定按钮位置，可以使用定位 */
  /* position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%); */
}
</style>
